package cn.buildoncloud.labor.workermanapplet.business.modules.services.impl;

import cn.buildoncloud.labor.workermanapplet.business.modules.services.EquipmentService;
import cn.buildoncloud.labor.workermanapplet.common.Constant;
import cn.buildoncloud.labor.workermanapplet.common.base.service.BaseServiceImpl;
import org.nutz.dao.Dao;
import org.nutz.dao.Sqls;
import org.nutz.dao.entity.Record;
import org.nutz.dao.sql.Sql;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class EquipmentServiceImpl extends BaseServiceImpl<Map> implements EquipmentService {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    public EquipmentServiceImpl(Dao dao) {
        super(dao);
    }

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public boolean existenceEquipment(String uniqueIdentity) {
        StringBuilder sb = new StringBuilder("SELECT COUNT(id) count FROM sys_equipment WHERE unique_identity = @unique_identity");

        Sql sql = Sqls.create(sb.toString());
        sql.setParam("unique_identity", uniqueIdentity);
        List<Record> result = this.list(sql);
        int count = Integer.parseInt(((Map) result.get(0)).get("count").toString());
        return count > 0;
    }

    @Override
    public boolean existenceEquipmentModelId(String equipmentModelId) {
        StringBuilder sb = new StringBuilder("SELECT count(id) count from sys_equipment_model WHERE id = @id");
        Sql sql = Sqls.create(sb.toString());
        sql.setParam("id", equipmentModelId);
        List result = this.list(sql);
        int count = Integer.parseInt(((Map) result.get(0)).get("count").toString());
        return count > 0;
    }

    @Override
    public boolean isOnline(String uniqueIdentity) {
        String lastDateStr = redisTemplate.opsForValue().get(Constant.MACHINE_HEART_KEY + uniqueIdentity);
        if (lastDateStr == null) {
            return false;
        }
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date lastDate = null;
        try {
            lastDate = sf.parse(lastDateStr);
        } catch (ParseException e) {
            log.error(e.getMessage(), e);
            return false;
        }
        if ((System.currentTimeMillis() - lastDate.getTime()) < 5 * 60 * 1000) {
            return true;
        }
        return false;
    }

}
